﻿using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using NthDownload.BL.Persistence;
using NthDownload.Common.Plugins;
using NthDownload.Common.ViewModels;
using NthDownload.Contracts.Plugins;

namespace NthDownload.ViewModels
{
    public class LoadingViewModel : ViewModelScreenBase
    {
        #region Class Members

        private string _description;

        #endregion Class Members

        #region Methods

        public void Load()
        {
            Task coordinationTask = new Task(() =>
            {
                UISynchronizationContext.Send(state => Description = "Download Plugins", null);
                Task downloadPluginsTask = DownloadPluginService.LoadPlugins();
                downloadPluginsTask.Wait();

                UISynchronizationContext.Send(state => Description = "Bandwidth Provider Plugins", null);
                Task bandwidthProviderPluginsTask = BandwidthProviderPluginService.LoadPlugins();
                bandwidthProviderPluginsTask.Wait();

                UISynchronizationContext.Send(state => Description = "Profile", null);
                Task profileTask = ProfilePersistenceService.Load();
                profileTask.Wait();

                UISynchronizationContext.Send(state =>
                {
                    NavigationService.Show(new MainViewModel());
                    TryClose();
                }, null);
            });

            coordinationTask.Start();
        }

        #endregion Methods

        #region Properties

        /// <summary>
        /// The description of what is being loaded
        /// </summary>
        public string Description
        {
            get
            {
                return _description;
            }
            set
            {
                _description = value;
                NotifyOfPropertyChange(() => Description);
            }
        }

        /// <summary>
        /// The download plugin service
        /// </summary>
        [Import(typeof(DownloadPluginDirectoryService))]
        public IPluginService DownloadPluginService { get; set; }

        /// <summary>
        /// The bandwidth provider plugin service
        /// </summary>
        [Import(typeof(BandwidthProviderPluginDirectoryService))]
        public IPluginService BandwidthProviderPluginService { get; set; }

        /// <summary>
        /// Profile persistence service
        /// </summary>
        [Import(typeof(NthProfilePersistenceService))]
        public NthProfilePersistenceService ProfilePersistenceService { get; set; }

        /// <summary>
        /// The Synchronization Context of the executing thread
        /// </summary>
        [Import(typeof(SynchronizationContext), AllowRecomposition = true)]
        public SynchronizationContext UISynchronizationContext { get; set; }

        #endregion Properties
    }
}
